package controller;

import bean.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import service.StudentService;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class RegistServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        Integer id = Integer.valueOf(request.getParameter("id"));
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        Integer age = Integer.valueOf(request.getParameter("age"));

        //获取spring的容器对象
        //ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //配置好监听器和全局参数后，使用框架中的方法获取spring容器对象
        WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        System.out.println("spring容器对象：" + ac);
        /**
         * 开启服务器后，每次执行注册操作，都使用的是一个spring容器对象，创建时间一直是一个
         * spring容器对象：Root WebApplicationContext, started on Mon Oct 25 15:03:40 CST 2021
         */

        //创建StudentService代理对象,执行业务方法
        StudentService studentService = (StudentService) ac.getBean("studentService");
        Student student = new Student(id, name, email, age);
        int i = studentService.registStudent(student);
        if (i > 0) {
            request.getRequestDispatcher("/registSuccess.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("/registFailure.jsp").forward(request, response);
        }

    }
}
